import Tabs, { TabsProps } from '@/components/Tabs';
import { stationControllerGetStation as getDetail } from '@/services/ess/station';
import { useIntl, useModel } from '@umijs/max';
import { useEffect, useRef, useState } from 'react';
import BaseInfo from './components/BaseInfo';
import EnergyPrice, { EnergyPriceToolBarRender } from './components/EnergyPrice';
import PhotovoltaicsPrice, { PvPriceToolBarRender } from './components/PhotovoltaicsPrice';

const Index = ({}) => {
  const { initialState } = useModel('@@initialState');
  const stationId = Number(initialState?.stationId);
  const [detailInfo, setDetailInfo] = useState<API.StationInfo | null>(null);

  useEffect(() => {
    if (stationId) {
      getDetail({ id: stationId }).then((res) => {
        if (res?.data) {
          setDetailInfo(res.data);
        } else {
          setDetailInfo(null);
        }
      });
    }
  }, [stationId]);

  const electricityPriceRef = useRef(null);
  const pvElectricityPriceRef = useRef(null);
  const intl = useIntl();
  let items: TabsProps['items'] = [
    {
      key: '1',
      label: intl.formatMessage({ id: 'electricityPrice.energyStorageElectricityPrice' }),
      children: (
        <EnergyPrice
          ref={electricityPriceRef}
          sitePriceType={detailInfo?.priceType}
          stationId={stationId}
          eleType={1}
        />
      ),
    },
  ];

  if (initialState?.isPhotovoltaic) {
    items.push({
      key: '2',
      label: intl.formatMessage({
        id: 'electricityPrice.photovoltaicPowerGenerationElectricityPrice',
      }),
      children: (
        <PhotovoltaicsPrice ref={pvElectricityPriceRef} stationId={stationId} eleType={2} />
      ),
    });
  }

  const [activeKey, setActiveKey] = useState(items?.[0]?.key);

  const onChange = (key: string) => {
    setActiveKey(key);
  };

  return (
    <>
      <BaseInfo detailInfo={detailInfo} />
      <div style={{ marginTop: 20 }}>
        <Tabs
          activeKey={activeKey}
          items={items}
          onChange={onChange}
          tabBarExtraContent={
            activeKey === '1' ? (
              <EnergyPriceToolBarRender tableRef={electricityPriceRef} />
            ) : (
              <PvPriceToolBarRender tableRef={pvElectricityPriceRef} />
            )
          }
          tabsLevel={2}
        />
      </div>
    </>
  );
};

export default Index;
